package com.springboot.facade.impl;

import com.alibaba.fastjson.JSON;
import com.springboot.dto.Result;
import com.springboot.dto.ResultModel;
import com.springboot.facade.UserServiceFacade;
import com.springboot.jpa.entity.User;
import com.springboot.jpa.repository.UserRepository;
import com.springboot.mybatis.mapper.UserMapper;
import com.springboot.req.UserReq;
import com.springboot.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("userServiceFacade")
public class UserServiceFacadeImpl implements UserServiceFacade {
    private static Logger logger = LoggerFactory.getLogger(UserServiceFacadeImpl.class);

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRepository userRepository;

    @Override
    public Result<String> register(UserReq userReq) {
        return null;
    }

    @Override
    @Transactional
    public Result<String> insertUser() {
        logger.info("insertUser start.");
        com.springboot.mybatis.pojo.User mybatisUser = new com.springboot.mybatis.pojo.User();
        mybatisUser.setUsername("mybatis .. name");
        mybatisUser.setPassword("pw:mybatis ... password");
//        userMapper.insertUser(mybatisUser);
        System.out.println(mybatisUser);
        logger.info("insertUser .mybatisUser:{}", JSON.toJSONString(mybatisUser));

        com.springboot.jpa.entity.User jpaUser = new com.springboot.jpa.entity.User();
        jpaUser.setUsername("jpa .. name");
        jpaUser.setPassword("pw:jpa ... password");
        jpaUser = userRepository.save(jpaUser);
        logger.info("insertUser .jpaUser:{}", JSON.toJSONString(jpaUser));

        logger.info("insertUser end.");
        return ResultModel.successResult("新增成功。");
    }

    @Override
    public Result<String> loginIn(UserReq userReq) {
        return ResultModel.successResult("登陆成功！");
    }

    @Override
    public Result<UserVo> findByUsername(String username) {
        logger.info("findByUsername start. username:{}", username);
        User user = userRepository.findByUsername(username);
        UserVo vo = new UserVo();
        BeanUtils.copyProperties(user, vo);
        logger.info("findByUsername end .{}", JSON.toJSONString(vo));
        return ResultModel.successResult(vo);
    }
}
